import React, { useState, useEffect } from "react";
import { useLocation, useNavigate } from "react-router-dom";
import { DocumentTemplateAPI } from "@/api/DocumentTemplate";
import { Button } from "@/components/ui/button";
import { ArrowLeft, Save } from "lucide-react";
import { createPageUrl } from "@/utils";
import MarkdownTemplateEditor from "../components/document-templates/MarkdownTemplateEditor";

export default function DocumentTemplateEditorPage() {
  const [template, setTemplate] = useState(null);
  const [isLoading, setIsLoading] = useState(true);
  const [isSaving, setIsSaving] = useState(false);
  const [saveNotification, setSaveNotification] = useState(null);
  const location = useLocation();
  const navigate = useNavigate();

  useEffect(() => {
    const urlParams = new URLSearchParams(location.search);
    const templateId = urlParams.get('id');
    if (templateId) {
      loadTemplate(templateId);
    } else {
      navigate(createPageUrl("DocumentTemplates"));
    }
  }, [location.search, navigate]);

  const loadTemplate = async (id) => {
    setIsLoading(true);
    try {
      const data = await DocumentTemplateAPI.get(id);
      setTemplate(data);
    } catch (error) {
      console.error("加载模板失败:", error);
      alert("加载模板失败，将返回列表页");
      navigate(createPageUrl("DocumentTemplates"));
    } finally {
      setIsLoading(false);
    }
  };

  const handleSave = async (updatedTemplateData) => {
    if (!template) return;
    setIsSaving(true);
    try {
      await DocumentTemplateAPI.update(template.id, updatedTemplateData);
      // Optimistically update local state or reload
      setTemplate(prev => ({ ...prev, ...updatedTemplateData }));
      // 显示成功通知而不是alert
      setSaveNotification({ type: 'success', message: '模板保存成功' });
      setTimeout(() => setSaveNotification(null), 3000);
    } catch (error) {
      console.error("保存模板失败:", error);
      // 错误仍使用alert，因为需要用户关注
      alert("保存失败: " + (error.message || "未知错误"));
    } finally {
      setIsSaving(false);
    }
  };

  const handleCancel = () => {
    navigate(createPageUrl("DocumentTemplates"));
  };

  if (isLoading) {
    return (
      <div className="p-6">
        <div className="text-center py-12">
          <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600 mx-auto mb-4"></div>
          <p>加载模板编辑器...</p>
        </div>
      </div>
    );
  }

  return (
    <div className="p-6 bg-gray-50 min-h-screen">
      {/* 成功通知条 */}
      {saveNotification && (
        <div className={`fixed top-4 right-4 z-50 px-4 py-3 rounded-lg shadow-lg border transition-all duration-300 ${
          saveNotification.type === 'success' 
            ? 'bg-green-50 text-green-800 border-green-200' 
            : 'bg-red-50 text-red-800 border-red-200'
        }`}>
          <div className="flex items-center gap-2">
            <div className="w-5 h-5 bg-green-500 rounded-full flex items-center justify-center">
              <div className="w-2 h-2 bg-white rounded-full"></div>
            </div>
            <span className="text-sm font-medium">{saveNotification.message}</span>
          </div>
        </div>
      )}

      <div className="mb-6">
        <Button 
          variant="ghost" 
          onClick={() => navigate(createPageUrl("DocumentTemplates"))}
          className="mb-4"
        >
          <ArrowLeft className="w-4 h-4 mr-2" />
          返回模板列表
        </Button>
      </div>

      {template && (
        <MarkdownTemplateEditor
          key={template.id} // Add key to force re-mount on template change
          template={template}
          onSave={handleSave}
          onCancel={handleCancel}
        />
      )}
    </div>
  );
}